<template>
	<view class="page-container auth-container">
		<uni-nav-bar dark :fixed="true" status-bar title="授权登录" :border="false" />
		<view class="my-profile">
			<image class="image profile-bg" src="../../static/logo.jpg" mode="aspectFill" />
		</view>
		<view class="p-5 auth-content">
			<!-- <image class="image about-logo-image" :src="logo" mode="aspectFit" /> -->
			<view class="d-flex flex-column justify-content-center mt-5">
				<!-- #ifdef MP-WEIXIN -->
				<!-- <text class="bg-primary-600 fs_18 auth-btn text-center" v-if='isFir' @click="getUserProfile">授权登录</text> -->
				<button class="bg-primary-600 fs_18 auth-btn text-center login" open-type="getPhoneNumber"
					@getphonenumber="getPhoneNumber">手机号登录</button>
				<text class="bg-primary-600 fs_18 auth-btn text-center mt-3" @click="goBack">取消登录</text>
				<!-- #endif -->
			</view>
		</view>
		<privacy-popup ref="privacyComponent" position="center"></privacy-popup>
	</view>
</template>

<script>
	let App = getApp();
	import {
		mapState,
		mapGetters,
		mapActions,
		mapMutations
	} from 'vuex'
	import privacyPopup from '../../components/privacy-popup/privacy-popup.vue'
	export default {
		data() {
			return {
				authBg: require("@/static/my_navbar_auth.png"),
				logo: require("@/static/uni.png"),
				isWeChat: App.globalData.isWeChat,
				userInfo: {},
				isFir: 1,
				isSec: 0,
			}
		},
		components: {
			privacyPopup
		},
		onLoad() {
			// this.initLogo();

			// 记录上一页
			var pages = getCurrentPages(); //当前页
			var beforePage = pages[pages.length - 2]; //上个页面
			var beforePageFullPath = "";
			if (beforePage) {
				beforePageFullPath = "/" + beforePage.route;
			} else {
				beforePageFullPath = "/pages/index/index";
			}
			// 将上一页的路由保存到storage
			uni.setStorageSync('beforePageFullPath', beforePageFullPath);
		},
		onShow() {
			this.getLogin();
		},
		computed: {
			...mapState(['accessToken'])
		},
		methods: {
			...mapMutations(['setStoreAccessToken']),
			getLogin() {
				let that = this;
				wx.login({
					success: res => {
						this.userInfo.code = res.code;
					}
				})
			},
			// 获取logo
			initLogo() {
				this.$api.aboutUs({
					name: 'logo',
				}).then(res => {
					if (res.code == 0) {
						this.logo = this.$globalUrl.baseUrl + res.data.value;
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				});
			},

			// 授权
			getUserProfile: function() {
				// #ifdef MP-WEIXIN
				// 展示加载框
				uni.showLoading({
					title: '加载中',
				});
				setTimeout(function() {
					uni.hideLoading();
				}, 500);
				uni.getUserProfile({
					desc: '登录后可同步数据',
					success: async (obj) => {
						console.log('obj', obj)
						this.userInfo.encryptedData = obj.encryptedData;
						this.userInfo.iv = obj.iv;
						this.isFir = 0;
						this.isSec = 1;
					},
					fail: (err) => {
						console.log('err', err)
						uni.showToast({
							title: '授权已取消',
							icon: 'error',
							mask: true,
						});
					},
					complete: () => {
						// 隐藏loading
						uni.hideLoading();
					},
				});
				//#endif
			},
			// 获取手机号
			// 只有已经认证的小程序才能获取手机号或者使用云函数获取加密数据解密
			getPhoneNumber(e) {
				// console.log('e1',e);
				// 参数e是绑定的授权方法自动传入过来的, 
				//主要是为了拿到vi和encryptedData值从后台换取用户联系方式
				if ("getPhoneNumber:ok" != e.detail.errMsg) {
					wx.showToast({
						icon: 'none',
						title: '快捷登陆失败'
					})
					return;
				}
				// console.log('e',e);
				let iv = e.detail.iv;
				let encryptedData = e.detail.encryptedData;
				// let code = this.data.wxCode;
				let _this = this;
				//调用后台接口获取用户手机号码
				let params = {
					code: this.userInfo.code,
					phoneEncryptedData: encryptedData,
					phoneIv: iv,
					userEncryptedData: '',
					userIv: ''
				}
				params = JSON.stringify(params)
				console.log('params', params)
				this.accredit(params);
			},
			// 解析URL 参数
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) ||
					[, ''
					])[1]
					.replace(/\+/g, '%20')) || null
			},

			// 微信公众号授权后调接口-跳转
			wx_auth(code) {
				// 接口的跳转
				this.$api.get_wx_auth({
					code: code,
					signcode: "",
				}).then(authRes => {
					if (authRes.code == 0) {
						if (authRes.data.need_login == 1) { // 是第一次授权，需要跳转到注册页面
							uni.setStorageSync('user_info', authRes.data.accessToken);
							uni.reLaunch({
								url: '/pages/register/register',
							})
						} else {
							uni.showToast({
								title: '已授权',
								icon: 'success'
							});
							uni.setStorageSync('user_token', authRes.data.data);
							var beforePageFullPath = uni.getStorageSync('beforePageFullPath');
							var url_g = window.location.href.split("?code=")[0];
							setTimeout(() => {
								window.location.href = url_g + "#" + beforePageFullPath;
							}, 1000)
						}
					} else {
						uni.showToast({
							title: authres.msg,
							icon: 'none'
						});
					}
				});
			},
			// 返回
			goBack() {
				uni.navigateBack({
					success: () => {
						let page = getCurrentPages().pop(); //跳转页面成功之后
						if (!page) {
							return;
						} else {
							page.onLoad(page.options); // page自带options对象.
						}
					}
				})
			},
			// 授权
			accredit(params) {
				this.$api.get_mini_auth(params).then(authRes => {
					if (authRes.code == 200) {
						uni.showToast({
							title: '已授权',
							icon: 'none'
						});
						uni.removeStorageSync('user_token');
						uni.setStorageSync('user_token', authRes.data.accessToken);
						this.setStoreAccessToken(authRes.data.accessToken);
						setTimeout(() => {
							uni.navigateBack({
								success: () => {
									let page = getCurrentPages().pop(); //跳转页面成功之后
									if (!page) {
										return;
									} else {
										page.onLoad(page.options); // page自带options对象.
									}
								}
							})
						}, 1000);
					} else {
						uni.showToast({
							title: authRes.msg,
							icon: 'none'
						});
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login {
		overflow: hidden;
	}

	.my-profile {
		margin-top: 50rpx;

		.image {
			width: 300rpx;
			height: 300rpx;
			margin: 0 auto;
		}
	}

	.padding-sm {
		padding: 22upx;
	}

	.text-center {
		text-align: center;
	}

	.text-xl {
		font-size: 36upx;
	}

	.padding-xl {
		padding: 50upx;
	}

	.text-letter {
		letter-spacing: 1upx;
		line-height: 1.5;
	}

	.flex {
		display: flex;
	}

	.justify-around {
		justify-content: space-around;
	}
</style>
